<template>
	<div class="front-padding" id="currencyType">
		<div style="height: 100%">
			<div class="widgets bg-white">
				<el-input v-model.trim="searchText" class="search__input" placeholder="输入搜索内容" @keyup.enter.native="search"></el-input>
	            <el-button type="primary" @click="search">查询</el-button>
	            <div class="btn-group right">
	            	<el-button type="info" @click="refresh">刷新</el-button>
	                <el-button type="primary" @click="add">新增</el-button>
	                <el-button type="danger" v-if="multipleSelection.length <= 0" disabled>删除</el-button>
	                <el-button type="danger" v-else @click="del">删除</el-button>
	                <el-button type="danger" v-if="multipleSelection.length <= 0" disabled>禁用</el-button>
	                <el-button type="danger" v-else @click="disabedBtn(0, '禁用')">禁用</el-button>
	                <el-button type="success" v-if="multipleSelection.length <= 0" disabled>启用</el-button>
	                <el-button type="success" v-else @click="disabedBtn(1, '启用')">启用</el-button>
	                <el-button-group class="btn-other">
	                    <el-button v-if="multipleSelection.length <= 0" disabled>
	                        <img src="../../../assets/images/export.png" alt="">
	                    </el-button>
	                    <el-button v-else @click="exportExcel" title="导出">
	                        <img src="../../../assets/images/export.png" alt="">
	                    </el-button>
	                    <el-button title="导入">
	                        <el-upload class="upload-demo" :action="$url + 'currency/importCurrency'" :show-file-list="false" multiple style="display: inline-block;" :on-success="importExcelSuccess">
	                            <img src="../../../assets/images/import.png" alt="">
	                        </el-upload>
	                    </el-button>                        
	                    <el-button title="打印">
	                        <img src="../../../assets/images/print.png" alt="">
	                    </el-button>
	                    <el-button title="帮助">
	                        <img src="../../../assets/images/help.png" alt="">
	                    </el-button>
	                </el-button-group>
	            </div>
			</div>
			<div class="table top-bottom bj bg-white">
                <el-scrollbar style="height: 100%;">
    				<el-table :data="tableData" border highlight-current-row ref="mtd" @selection-change="handleSelectionChange" @row-contextmenu="rowContextmenu">
    	                <el-table-column type="selection" align="center"></el-table-column>
    	                <el-table-column type="index" label="序号" width="70" align="center"></el-table-column>
    	                <el-table-column property="name" label="名称" align="center"></el-table-column>
    	                <el-table-column property="exchangeRate" label="汇率" align="center"></el-table-column>
    	                <el-table-column property="convertType" label="折算方式" width="200" align="center">
    	                    <template slot-scope="scope">
    	                        <span>{{ scope.row.convertType == 1 ? "原币*汇率=本位币" : "原币/汇率=本位币" }}</span>
    	                    </template>
    	                </el-table-column>
    	                <el-table-column property="decimals" label="小数位数" align="center"></el-table-column>
    	                <el-table-column property="fixedExchangeRate" label="汇率类别" align="center">
    	                    <template slot-scope="scope">
    	                        <span>{{ scope.row.fixedExchangeRate == 1 ? "固定汇率" : "浮动汇率" }}</span>
    	                    </template>
    	                </el-table-column>
    	                <el-table-column property="state" label="状态" align="center">
    	                    <template slot-scope="scope">
    	                        <span v-if="scope.row.state === 1" style="color: green;">已启用</span>
    	                        <span v-else style="color: #f00;">已禁用</span>
    	                    </template>
    	                </el-table-column>
    	                <el-table-column label="操作" align="center">
    	                    <template slot-scope="scope">
    	                        <el-button type="text" size="small" @click="update(scope.row.id)">修改</el-button>
    	                    </template>
    	                </el-table-column>
    	            </el-table>
                </el-scrollbar>
			</div>
		</div>
        <!-- 右键菜单组件 -->
        <bj-menu :isShow.sync="menus.isShow" :disabled="menus.disabled" @handlerClick="handlerClick"/>
	</div>
</template>
<script>
export default {
	data() {
		return {
			searchText: '',
			tableData: this.$store.state.currencyTypeStore.tableData,
			searchResult: this.$store.state.currencyTypeStore.searchResult,		//搜索数据
			multipleSelection: [],          //选中的行数据集合
			selectRowId: [],            //选中的行数据id集合
			menus: {
				isShow: false,
				row: null,
				disabled: ['打印']
			}
		}
	},
	watch: {
        searchText(newVal) {
            if(!newVal) {
                this.$store.dispatch('currencyTypeStore/getTableData');
            }
        }
    },
	methods: {
		search() {
			let data = this.searchResult,
                newArr = [];
            if(this.searchText) {
                data.forEach(item => {
                    if(item['name'].indexOf(this.searchText) > -1 || item['toSimplePinyin'].indexOf(this.searchText) > -1 || item['toNamePinyin'].indexOf(this.searchText) > -1) {
                        newArr.push(item);
                    }
                });
                this.$store.commit('currencyTypeStore/updateTableData', newArr);
            }
		},
		handleSelectionChange(arr) {
			this.multipleSelection = arr;
            this.selectRowId = [];
            for(var i = 0; i < this.multipleSelection.length; i++) {
                this.selectRowId.push(this.multipleSelection[i]['id']);
            }
		},
		refresh() {
			const loading = this.$loading({
                lock: true,
                text: '数据刷新中...',
                spinner: 'el-icon-loading',
                background: '#fff'
            });
            setTimeout(() => {
            	if(this.searchText) this.searchText = '';
                loading.close();
            }, 1000);
		},
		add() {			//新增
			this.$store.commit('currencyTypeStore/updateRowId');
			this.$util.openLayerIframe({title: '币别-新增', zIndex: 13, width: '550px', height: '470px', url: this.$domain + '/#/basicData/currencyType/form'});
		},
		update(id) {	//修改
			this.$store.commit('currencyTypeStore/updateRowId', id);
			this.$util.openLayerIframe({title: '币别-修改', zIndex: 13, width: '550px', height: '425px', url: this.$domain + '/#/basicData/currencyType/form'});
		},
		del(id) {		//删除
			this.$confirm('此操作将永久删除该文件, 是否继续？', '删除提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                //开始求删除
                this.$http.post('currency/deleteCurrency', id ? JSON.stringify([id]) : JSON.stringify(this.selectRowId), {
					headers: {'Content-Type': 'application/json'}
				}).then(res => {
                    if(res.data.code == 20001) {
                        this.$message({message: '数据删除成功', type: 'success', duration: 1500});
                        setTimeout(() => {
                            this.$store.dispatch('currencyTypeStore/getTableData', this.$url + 'currency/findCurrency');
                        }, 500);
                    } else {
                        this.$message.error(res.data.msg);
                    }
                }).catch(err => {
                    this.$message.error(err);
                })
            });
		},
		disabedBtn(status, msg, row) {         //禁用、启用
			let multipleSelection = row ? [row] : this.multipleSelection;		//如果不是右键点击禁用、启用，就拿表格选中的数据
            for(var i = 0; i < multipleSelection.length; i++) {
                if(multipleSelection[i]['state'] == status) {
                    this.$alert(msg + '失败，其中包含已'+ msg +'选项，重新选择！', msg + '提示', {
                        confirmButtonText: '确定'
                    });
                    return false;
                }
            }
            this.$http.post('currency/startOrDisableCurrency?state=' + status, row ? JSON.stringify([row['id']]) : JSON.stringify(this.selectRowId), {
				headers: {'Content-type': 'application/json;charset=UTF-8'}
			}).then(res => {
                if(res.data.code == 20001) {
                    this.$message({message: msg + '成功', type: 'success', duration: 2000});
                    setTimeout(() => {
                        this.$store.dispatch('currencyTypeStore/getTableData');
                    }, 1000);
                } else {
                    this.$message.error(this.data.msg);
                }
            });
		},
		exportExcel() {
			if(this.multipleSelection.length > 0) {
                var idSting = this.selectRowId.join(',');           //将[1,2,3]格式转为 "1,2,3"
                this.$http.get(this.$url + 'currency/exportCurrency',{params: { idList: idSting }}).then(res => {
                    this.$message({message: '导出成功', type: 'success'});
                    window.location.href = this.$url + 'currency/exportCurrency?idList=' + idSting;          //导出时触发
                }).catch(err => {
                    this.$message.error(err);
                })
            } else {
                this.$message({message: '选择你要导出的数据', type: 'warning', duration: 2000});
            }
		},
		importExcelSuccess(res) {
			if(res.code === 20001) {        //导入成功后回调该函数
                this.$message({message: '导入成功', type: 'success'});
                setTimeout(() => {
                    this.$store.dispatch('currencyTypeStore/getTableData', this.$url + 'currency/findCurrency');
                }, 1000);
            }else{
                this.$message({message: res.msg, type: 'error'});
         	}
		},
		rowContextmenu(row, event) {           //某一行右键点击时触发
			event.preventDefault();     		//阻止默认事件
			this.menus.isShow = true;			//显示右键菜单
			this.menus.row = row;				//存储当前所在行数据
            let x = event.clientX,
                y = event.clientY,
                pw = $('.front-padding').outerWidth(true),
                ph = $('.front-padding').outerHeight(true),
                cw = $('.bj-menu').outerWidth(true),
                ch = $('.bj-menu').outerHeight(true);
            //处理边界
            if(x <= 0) x = 0;
            if(y <= 0) y = 0;
            if(x >= pw - cw) x = pw - cw - 5;
            if(y >= ph - ch) y = ph - ch - 5;
            $('.bj-menu').css({left: x + 'px', top: y + 'px'});
		},
		handlerClick(index) {		//右键点击菜单选项触发该函数
			switch(index) {
				case 1:
					this.refresh();
					break;
				case 2:
					this.add();
					break;
				case 3:
					this.update(this.menus.row.id);
					break;
				case 4:
					this.del(this.menus.row.id);
					break;
				case 5:
					this.disabedBtn(0, '禁用', this.menus.row);
					break;
				case 6:
					this.disabedBtn(1, '启用', this.menus.row);
					break;
				case 8:
					this.tableMove(this.tableData, this.menus.row, index);
					break;
				case 9:
					this.tableMove(this.tableData, this.menus.row, index);
					break;
				case 10:
					this.tableMove(this.tableData, this.menus.row, index);
					break;
				case 11:
					this.tableMove(this.tableData, this.menus.row, index);
					break;
				default: break;
			}
		},
		tableMove(tableData, row, index) {			//上移、下移、置于顶层、置于底层
			switch(index) {
				case 8:
					if(tableData[0]['id'] !== row['id']) {
						let pos = tableData.indexOf(row);		//拿到当前row在数组中所在的位置
						tableData.splice(pos - 1, 0, tableData.splice(pos, 1)[0]);
					} else {
						//数组的第一位，不能上移
						this.$message({message: '已经是第一条了，不可上移', type: 'warning', duration: 1500});
					}
					break;
				case 9:
					if(tableData[tableData.length - 1]['id'] !== row['id']) {
						let pos = tableData.indexOf(row);
						tableData.splice(pos + 1, 0, tableData.splice(pos, 1)[0]);
					} else {
						//数组最后一位，不能下移
						this.$message({message: '已经是最后一条了，不可下移', type: 'warning', duration: 1500});
					}
					break;
				case 10:
					if(tableData[0]['id'] !== row['id']) {
						tableData.unshift(tableData.splice(tableData.indexOf(row), 1)[0]);		//向数组的开头插入row
					} else {
						//数组的第一位，不能置顶
						this.$message({message: '已经是第一条了，不可置顶', type: 'warning', duration: 1500});
					}
					break;
				case 11:
					if(tableData[tableData.length - 1]['id'] !== row['id']) {
						tableData.push(tableData.splice(tableData.indexOf(row), 1)[0]);
					} else {
						//数组最后一位，不能置底
						this.$message({message: '已经是最后一条了，不可置底', type: 'warning', duration: 1500});
					}
					break;
				default: break;
			}
		}
	},
	created() {
		this.$store.dispatch('currencyTypeStore/getTableData');
	}
}
</script>